#ifndef _FRAME_H
#define _FRAME_H

/*
 *  Frame.h
 *  openFrameworks
 *
 *  Created by Mar Canet Sola on 17/06/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */
#include "ofMain.h"
#include "UDPManager.h"

#pragma pack(push,1)
struct Packet
{
	unsigned short address;
	unsigned char r;
	unsigned char g;
	unsigned char b;
};

class FrameBuffer {
private:	
	int packageSize;	///< size of a package (address+color)
	int nrAddresses;    ///< total number of packages;
	int offsetRed;		///< offset of red color in package
	int offsetGreen;	///< offset of green color in package
	int offsetBlue;		///< offset of blue color in package
	
	#pragma pack(pop)
	struct Packet frameBuffer [ 1085 ];

	UDPManager* myUDPManager;
public:	
	FrameBuffer(string ip) {
		packageSize = 5;	///< size of a package (address+color)
		nrAddresses = 1085; ///< total number of packages;
		offsetRed = 2;		///< offset of red color in package
		offsetGreen = 3;	///< offset of green color in package
		offsetBlue = 4;		///< offset of blue color in package
		
		
		printf("%d %d %d\n", sizeof(unsigned short), sizeof(unsigned char), sizeof(Packet));
		// create array
		for (unsigned short address = 0; address < nrAddresses; address++) 
		{
			frameBuffer[address].address = address;
			frameBuffer[address].r = 0;
			frameBuffer[address].g = 0;
			frameBuffer[address].b = 0;
		}
		
		myUDPManager = new UDPManager();
		myUDPManager->Create();
		myUDPManager->Connect(ip.c_str(), 8080);
		//myUDPManager->Connect("192.168.7.121", 8080);
		myUDPManager->SetTimeoutSend(-1);

	}

	/**
	 * set all packages to the same color
	 */
	
	void cleanColor() 
	{	
		for (unsigned short address = 0; address < nrAddresses; address++) 
		{
			frameBuffer[address].address = address;
			frameBuffer[address].r = 1;
			frameBuffer[address].g = 1;
			frameBuffer[address].b = 1;
		}
	}
	/**
	 * set package at address to color
	 */
	void setColor(unsigned short address, unsigned char r, unsigned char g, unsigned char b) 
	{

			frameBuffer[address].address = address;
			frameBuffer[address].r = r;
			frameBuffer[address].g = g;
			frameBuffer[address].b = b;
	}

	/**
	 * get color from address
	 */
	ofColor getColor(unsigned short address) 
	{
			ofColor out;
			out.r = frameBuffer[address].r;
			out.g = frameBuffer[address].g;
			out.b = frameBuffer[address].b;
			return out;
	}

	/**
	 * send the complete UDP packet to localhost:8080 (might be necessary to change)
	 */
	
	void flush()
	{
		
		myUDPManager->Send( &frameBuffer, sizeof(Packet) * ( nrAddresses) );
	}

};

#endif
